import MyFormUploadButton from '@/components/MyFormUploadButton';
import { DeptResultItem } from '@/services/api/model/deptModel';
import { UserResultDetails, UserResultItem } from '@/services/api/model/usersModel';
import { getListName } from '@/services/api/tenants';
import { createItem, getItemDetails, updateItem } from '@/services/api/users';
import { findParentIds } from '@/utils';
// import { getDeptList } from '@/services/api/users';
import { PlusOutlined } from '@ant-design/icons';
import {
  ModalForm,
  ProForm,
  ProFormCascader,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Button, Form, message } from 'antd';
import React from 'react';
type CreateFormProps = {
  onCancel?: () => void;
  onSubmit?: (values: UserResultItem) => void;
  userId?: number;
  title?: string;
  trigger?: JSX.Element;
  tableData: DeptResultItem[];
};

const CreateForm: React.FC<CreateFormProps> = (props) => {
  const {
    onSubmit,
    userId,
    title = '添加',
    trigger = (
      <Button type="primary">
        <PlusOutlined />
        {title}
      </Button>
    ),
    tableData,
  } = props;
  // 取出缓存的账号密码
  const user_pas = localStorage.getItem('user_pas');
  const userPasInfo = user_pas ? JSON.parse(user_pas) : null;
  return (
    <ModalForm<UserResultItem>
      request={async () => {
        if (userId) {
          const res: UserResultDetails = await getItemDetails({ userId: userId });
          const tenantList = res.data.tenantList;
          console.log('res?.data?.user :>> ', res?.data?.user);
          return {
            ...res?.data?.user,
            tenantIds: tenantList?.map((item) => item.id),
            deptId: res?.data?.deptId,
          } as UserResultItem; //强转一下
        } else {
          return {} as UserResultItem;
        }
      }}
      title={`${title}用户`}
      modalProps={{
        // 关闭弹框是否销毁 (相当于直接进行了表单重置)
        destroyOnClose: true,
      }}
      trigger={trigger}
      onFinish={async (values) => {
        console.log(values);
        if (!userId) {
          await createItem({
            ...values,
          });
        } else {
          await updateItem({
            ...values,
            id: userId,
          });
        }
        if (onSubmit) {
          onSubmit(values);
        }
        message.success('提交成功');
        // 返回true 则关闭
        return true;
      }}
      initialValues={{}}
    >
      <ProForm.Group>
        <ProFormText
          width={'md'}
          label="用户名"
          name="username"
          rules={[
            {
              required: true,
              message: '请输入用户名',
            },
          ]}
          placeholder="请输入用户名"
        />
        <ProFormRadio.Group
          width={'md'}
          label="性别"
          name="sex"
          transform={(value) => {
            // 取id的最后一条
            const val = value === 0 ? '0' : value;
            // 此处注意返回的是一个对象
            return { sex: val };
          }}
          options={[
            {
              label: '男',
              value: 1,
            },
            {
              label: '女',
              value: 0,
            },
          ]}
        />
      </ProForm.Group>

      <ProForm.Group>
        <ProFormCascader
          width={'md'}
          // convertValue格式化默认值,有些情况是后台返回的数据格式不是组件想要的,通过此方法格式化
          convertValue={(value) => {
            if (value) {
              // 找到当前id的所有父id
              const ids = findParentIds(tableData, value);
              // 包含自己的
              return [...ids, value];
            } else {
              return [];
            }
          }}
          // 提交参数的单独转换,有些是后台接受的参数不是实际前端获取的参数,此处单独转换
          transform={(value) => {
            console.log('value :>> ', value);
            if (typeof value === 'number') {
              return { deptId: value };
            } else {
              // 取id的最后一条
              const val = value && value.length ? value[value.length - 1] : '';
              // 此处注意返回的是一个对象
              return { deptId: val };
            }
          }}
          // 注意 ant组件的原生配置 都要写在fieldProps下
          fieldProps={{
            changeOnSelect: true, //选择某一级而非最后一级
            fieldNames: {
              label: 'name',
              value: 'id',
            },
            options: tableData,
          }}
          name="deptId"
          label="选择部门"
          placeholder={'请选择'}
        />
        <ProFormSelect
          fieldProps={{
            mode: 'multiple',
            fieldNames: {
              value: 'tenantId',
              label: 'token',
            },
          }}
          width={'md'}
          name="tenantIds"
          label="选择租户"
          request={async () => {
            const msg = await getListName({
              ...userPasInfo,
            });
            const results = msg.data?.tenantList;
            return results ? results : [];
          }}
          placeholder="请选择"
          rules={[{ required: true, message: '请选择' }]}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormText
          width={'md'}
          label="手机"
          name="phone"
          rules={[
            {
              required: true,
              message: '请输入手机号',
            },
          ]}
          placeholder="请输入手机号"
        />
        <ProFormText
          width={'md'}
          label="密码"
          name="password"
          fieldProps={{
            type: 'password',
          }}
          rules={[
            {
              required: true,
              message: '请输入密码',
            },
          ]}
          placeholder="请输入密码"
        />
      </ProForm.Group>

      <ProForm.Group>
        <ProFormTextArea
          width={'md'}
          label="备注"
          name="remark"
          rules={[
            {
              required: true,
              message: '请输入备注',
            },
          ]}
          placeholder="请输入备注"
        />
        <Form.Item
          name="url"
          label="图片"
          rules={[
            {
              required: false,
              message: '请上传',
            },
          ]}
        >
          <MyFormUploadButton></MyFormUploadButton>
        </Form.Item>
      </ProForm.Group>
    </ModalForm>
  );
};

export default CreateForm;
